import { Toast } from 'antd-mobile'
import axios, { AxiosError, InternalAxiosRequestConfig } from 'axios'
import { getToken } from './storage'
import history from './history'
import store from '@/store'
import { logout, saveToken } from '@/store/actions/login'

const instance = axios.create({
  baseURL: 'http://geek.itheima.net/v1_0/',
  timeout: 5000,
})

// 添加请求拦截器
instance.interceptors.request.use(
  function (config) {
    const { token } = getToken()
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }

    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

// 添加响应拦截器
instance.interceptors.response.use(
  function (response) {
    // 对响应数据做点什么
    return response
  },
  async function (error: AxiosError<{ message: string }>) {
    if (!error.response) {
      Toast.show('服务器繁忙，请稍后再试')
      return Promise.reject(error)
    }
    if (error.response.status === 401) {
      const token = getToken()
      if (token.token && token.refresh_token) {
        try {
          const res = await axios.request({
            method: 'PUT',
            url: `http://geek.itheima.net/v1_0/authorizations`,
            headers: {
              Authorization: `Bearer ${token.refresh_token}`,
            },
          })
          store.dispatch(
            saveToken({
              token: res.data.data.token,
              refresh_token: token.refresh_token,
            })
          )
          return instance.request(
            error.config as InternalAxiosRequestConfig<any>
          )
        } catch (error) {
          store.dispatch(logout())
          history.replace('/login', { from: history.location.pathname })
        }
      } else {
        history.replace('/login')
      }
    }
    Toast.show(error.response.data.message)
    // 对响应错误做点什么
    return Promise.reject(error)
  }
)

export default instance
